<template>
  <basic-container>
    <avue-crud
      :option="option"
      :data="data"
      :page.sync="page"
      ref='crud'
      @row-save="rowSave"
      @row-del="rowDel"
      v-model="form"
      :permission="permissionList"
      @row-update="rowUpdate"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad">
      <template slot="menuRight">
        <table-right :crud='$refs.crud' :data='data' :add-permission="permission.public_material_add" :handle-add="addFn"
                     :refreshChange='refreshChange'>

          <el-button size="mini" type="text" icon="el-icon-delete"  @click="handleDelete" v-if="permission.public_material_delete">批量删除</el-button>

          <!--          <div class="top-bar__item iconDiv" @click="handleDelete" v-if="permission.publicproduct_masterdata_delete" >-->
          <!--            <i class="el-icon-delete" style="font-size:20px;"></i>-->
          <!--            <span style="font-size: 12px;color:#1e1e1e;">&nbsp;批量删除</span>-->
          <!--          </div>-->

          <!-- <el-button type="text" v-if="permission.publicproduct_masterdata_add" icon="el-icon-download" @click="downloadTemplateFn">下载模板</el-button>
          <el-upload style="display: inline-block" v-if="permission.publicproduct_masterdata_add" :show-file-list="false" :headers="headers" :on-success="uploadSuccess" :before-upload="beforeUpload" :on-error="uploadError" action="/api/prdinfo/uploadPrdInfo">
            <el-button type="text" slot="trigger" v-if="permission.publicproduct_masterdata_add" icon="el-icon-upload2" @click="importFn">导入</el-button>
          </el-upload>
          <el-button type="text" v-if="permission.publicproduct_masterdata_add" icon="el-icon-download" @click="exportFn">导出</el-button> -->
        </table-right>
      </template>

      <template slot-scope="{row}" slot="menu">
        <el-tooltip class="item" effect="dark" content="查看" placement="bottom">
          <el-button icon="el-icon-view" size="small" type="text" @click.stop="rowView(row)" v-if="permission.public_material_view"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
          <el-button icon="el-icon-edit" size="small" type="text"  @click.stop="rowEdit(row)" v-if="permission.public_material_edit"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
          <el-button icon="el-icon-delete" size="small" type="text" @click.stop="rowDel(row)"  v-if="permission.public_material_delete"></el-button>
        </el-tooltip>

      </template>
    </avue-crud>
    <el-dialog :title="title"
               v-dialogdrag
               :destroy-on-close="true"
               show-close
               :visible.sync="showDialog"
               width="50%"
               append-to-body='true'
               top="3%"
               :close-on-click-modal='false'>
      <material-main @reload="reload" @closeAfter="closeAfter" :openType="openType" :row="clickRow" :type="openType" @close="showDialog=false" v-if="showDialog" />
    </el-dialog>
  </basic-container>
</template>

<script>

import { mapGetters, mapState } from 'vuex';
import {init} from '@/mixins/init';
import { downloadFile, exportPrdInfo } from '@/api/project/productData/product.js';
import {culomnSpan, searchSpan} from "@/api/span";
import {getUnitList} from "@/api/basic/unit";
import MaterialMain from "@/views/publicmaterial/materialMain";
import {removematerial,materialList} from "@/api/project/productData/material";

export default {
  components: {MaterialMain},
  mixins: [init],
  data() {
    return {
      areaList: [],
      categoryList: [],
      showDialog:false,
      title:'',
      props: {
        label: 'dictValue',
        value: 'dictKey'
      },
      locList:[],
      loadings: false,
      index:0,
      defaultUnit: '',
      option: {
        // highlightCurrentRow: true,
        searchMenuSpan: searchSpan(2),
        dialogWidth: '1000',
        labelWidth: 120,
        searchGutter: 0,
        menuWidth: 120,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: true,
        menu:true,
        column: [
          {
            label: '物料编码',
            minWidth: 150,
            sortable: true,
            prop: 'materialNo',
            overHidden: true,
            search: true,
            searchSpan:culomnSpan(),
          },
          {
            label: '物料名称',
            prop: 'materialName',
            overHidden: true,
            search: true,
            searchSpan:culomnSpan(),
            minWidth: 150,
            sortable: true,
          },
          {
            label: '追溯类型',
            prop: 'traceAccuracy',
            type:'select',
            dicData:[
              {label:'批追',value:"1"},
              {label:'精追',value:"2"},
            ]
          },
          {
            label: '标箱数量',
            prop: 'boxCounts',
            overHidden: true,
            minWidth: 90,
            sortable: true,
          },
          {
            label: '计量单位',
            prop: 'unit',
            overHidden: true,
            minWidth: 90,
            sortable: true,
          }
        ],
      },
    };
  },

  computed: {
    ...mapGetters(['permission']), //权限映射
    ...mapState({
      headers: (state) => ({ 'Blade-Auth': `bearer ${state.user.token}` }),
    }),
    permissionList() {
      //按钮权限设置
      return {
        addBtn: this.vaildData(this.permission.publicproduct_masterdata_add, false),
        viewBtn: this.vaildData(this.permission.publicproduct_masterdata_view, false),
        delBtn: this.vaildData(this.permission.publicproduct_masterdata_delete, false),
        editBtn: this.vaildData(this.permission.publicproduct_masterdata_edit, false),
      };
    },
    productDrawingNos() {
      //所有勾选的id
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.productDrawingNo);
      });
      return ids.join(',');
    },
  },

  methods: {
    handleRowClick (row) {
      if (row.id == this.clickRow.id) {
        this.clickRow = {}
        this.$refs.crud.setCurrentRow()
        this.$EventBus.$emit('publicBtn', {add:this.permission.publicproduct_masterdata_add});
      } else {
        this.clickRow = row;
        this.$EventBus.$emit('publicBtn', {
          add:this.permission.publicproduct_masterdata_add,
          del:this.permission.publicproduct_masterdata_delete && row.productStatus ==1,
          edit:this.permission.publicproduct_masterdata_edit && row.productStatus != 3,
          view:this.permission.publicproduct_masterdata_view,
        });
      }
    },
    handleDelete() {
      //多选删除
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm(this.deleteFnMessageText, '提示', {
        confirmButtonText: this.confirmButtonText,
        cancelButtonText: this.cancelButtonText,
        type: 'warning',
      }).then(() => {
        return removematerial(this.ids);
      })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    addFn(){
      this.title = '新增产品主数据';
      this.openType = 'add';
      this.showDialog = true;
    },
    rowEdit(row){
      this.clickRow = row;
      this.title = '编辑产品主数据';
      this.openType = 'edit';
      this.showDialog = true;
    },
    rowView(row){
      this.clickRow = row;
      this.title = '查看产品主数据';
      this.openType = 'view';
      this.showDialog = true;
    },
    beforeUpload(file) {
      var reg = /^.*\.(?:xls|xlsx)$/i;
      if (!reg.test(file.name)) {
        this.$message.error('请上传xls或xlsx格式文件!');
        return false;
      }
      const isLt10M = file.size / 1024 / 1024 < 30;
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 30MB!');
        return false;
      }
      this.loading = true;
    },
    uploadError(err) {
      this.$message.error(JSON.parse(err.message).msg);
      this.loading = false;
      return false;
    },
    uploadSuccess() {
      this.onLoad(this.page);
      this.$message.success('操作成功');
    },
    downloadTemplateFn() {
      this.$confirm('确定下载模板吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          downloadFile(this.headers, '产品主数据.xls');
        })
        .catch(() => {});
    },
    exportFn() {
      if (this.data.length == 0) {
        this.$message.warning('暂无可导出数据，无法导出');
        return;
      }
      this.$confirm('确定导出数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          if (this.selectionList.length > 0) {
            let ids = this.selectionList.map((item) => item.id).join(',');
            let params = `ids=${ids}`;
            exportPrdInfo(this.headers, params, '产品主数据.xls');
          } else {
            let params = `materialNo=${this.query.materialNo || ''}&materialName=${
              this.query.materialName || ''
            }&innerDrawingNo=${this.query.innerDrawingNo || ''}&materialType=${this.query.materialType || ''}`;
            exportPrdInfo(this.headers, params, '产品主数据.xls');
          }
        })
        .catch(() => {});
    },
    rowSave(row, done, loading) {
      row.materialFlag = 'P';
      // row.category = row.categoryArr.join(',')
      row.warehouseArea = (typeof row.warehouseArea) == 'string' ? row.warehouseArea : row.warehouseArea.join(',')
      row.productionLineCode = row.productionLineCodeArr.join(',')
      product.productAdd(row).then(
        () => {
          if (this.goon) {
            loading();
            for (let key in this.$refs.crud.value) {
              this.$refs.crud.value[key] = null;
            }
            this.$set(this.form, 'version', '01');
            this.$set(this.form, 'quotaFlag', '2');
            this.$set(this.form, 'unit', this.defaultUnit);
            this.$set(this.form, 'warehouseArea', []);
            this.goon = false;
            this.onLoad(this.page);
          } else {
            this.onLoad(this.page);
            done();
          }
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        },
        (error) => {
          this.goon = false;
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      //行内的编辑事件触发
      row.warehouseArea = (typeof row.warehouseArea) == 'string' ? row.warehouseArea : row.warehouseArea.join(',')
      row.productionLineCode = row.productionLineCodeArr.join(',')
      product.productUpdate(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        (error) => {
          loading();
          // console.log(error);
        }
      );
    },
    rowDel(row) {
      //行内的删除事件触发
      this.$confirm(this.deleteFnMessageText, '提示', {
        confirmButtonText: this.confirmButtonText,
        cancelButtonText: this.cancelButtonText,
        type: 'warning',
      })
        .then(() => {
          return removematerial(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    reload () {
      this.onLoad(this.page)
      this.showDialog = false
    },
    closeAfter(){
      this.onLoad(this.page);
    },
    onLoad(page, params = this.query) {
      //加载table
      materialList(page.currentPage, page.pageSize, params).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        // this.data = data.records.map((item) => {
        //   item.warehouseArea = item.warehouseArea ? item.warehouseArea.split(',') : []
        //   return item;
        // });
        this.data = data.records;
        // this.$nextTick(() => {
        //   this.$refs.crud.setCurrentRow()
        // })

      });
    },
  },
  created() {
    // getUnitList().then((res) => {
    //   let data = res.data.data;
    //   const column = this.findObject(this.option.column, 'unit');
    //   column.dicData = data.map((item) => {
    //     return {
    //       label: item.name + '(' + item.code + ')',
    //       value: item.code,
    //     };
    //   });
    // });
  },
};
</script>

